import numpy as np
"""
{{a -> -((n sumxy - sumx sumy)/(sumx^2 - n sumx2)), 
  b -> -((-sumx sumxy + sumx2 sumy)/(sumx^2 - n sumx2))}}
"""
def leastSquaresLine(points):
    """最小二乘拟合直线"""
    sumx = 0
    sumy = 0
    sumxy = 0
    sumx2 = 0
    n = len(points)
    for i in range(n):
        x = points[i, 0, 0]
        y = points[i, 0, 1]
        sumx += x
        sumy += y
        sumx2 += x**2
        sumxy += x * y
    v1 = (sumx**2 - n * sumx2)
    v2 = (n * sumxy - sumx * sumy)
    a = -(v2/v1)
    b = (sumy - sumx * a) / n

    return (a, b)


if __name__ == "__main__":
    ps = []
    for i in range(10):
        ps.append([[5, i]])

    points = np.array(ps)
    leastSquaresLine(points)